﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MvcEngine.Core.Validation
{
    /// <summary>
    /// Checks whether the value is within a specified range of values.
    /// </summary>
    public class RangeValidatorAttribute : FieldValidatorAttribute
    {
        private int minValue;
        private int maxValue;

        /// <summary>
        /// Initializes a new instance of the <see cref="RangeValidatorAttribute"/> class.
        /// </summary>
        /// <param name="minValue">The min value.</param>
        /// <param name="maxValue">The max value.</param>
        public RangeValidatorAttribute(string message, int minValue, int maxValue)
            : base(message)
        {
            this.minValue = minValue;
            this.maxValue = maxValue;
            ErrorMessage = string.Format(Message, minValue.ToString(), maxValue.ToString());
        }

        /// <summary>
        /// Determines whether the specified value is valid.
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <returns>
        /// 	<c>true</c> if the specified value is valid; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsValid(object value)
        {
            if (value is int)
            {
                int val = (int)value;
                if (val >= minValue && val <= maxValue)
                {
                    return true;
                }
                return false;
            }
            else
            {
                throw new InvalidOperationException("RangeValidatorAttribute validator can applied only to integer properties");
            }
        }
    }
}
